package com.zretc.kscxmz.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.zretc.kscxmz.entity.FileInfo;
import com.zretc.kscxmz.entity.Mail;
import com.zretc.kscxmz.services.MailService;
import com.zretc.kscxmz.util.SendMailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zengyanjun
 * @date 2020-07-23
 */
@Controller
public class MailController {
    Logger logger = LoggerFactory.getLogger(MailController.class);
    @Autowired
    private MailService mailService;

    /**
     * 获取发件箱、收件箱、草稿箱数据
     * @param type
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/getMails")
    @ResponseBody
    public PageInfo<Mail> getMails(@RequestParam String type,
                                   @RequestParam String userId,
                                   @RequestParam String pageNum,
                                   @RequestParam String pageSize){
        Map<String,String> map = new HashMap<>();
        map.put("type",type);
        map.put("userId",userId);
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        logger.info("=====参数："+map);
        PageInfo<Mail> mailsByType = mailService.getMailsByType(map);
        logger.info("获取邮箱列表");
        logger.info("====结果集："+mailsByType);
        return mailsByType;
    }

    /**
     * 根据条件查询邮件
     * @param type
     * @param userId
     * @param pageNum
     * @param pageSize
     * @param condition
     * @param searchContent
     * @return
     */
    @RequestMapping("/getMailsBySearch")
    @ResponseBody
    public PageInfo<Mail> getMailsBySearch(@RequestParam String type,
                                           @RequestParam String userId,
                                           @RequestParam String pageNum,
                                           @RequestParam String pageSize,
                                           @RequestParam String condition,
                                           @RequestParam String searchContent){
        Map<String,String> map = new HashMap<>();
        map.put("type",type);
        map.put("userId",userId);
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        map.put("condition",condition);
        map.put("searchContent",searchContent);
        PageInfo<Mail> mailsByConditions = mailService.getMailsByConditions(map);
        return mailsByConditions;
    }

    /**
     * 删除邮件（改变邮件状态，is_del：1为删除，0为未删除的）
     * @param type
     * @param userId
     * @param mailIdList
     * @return
     */
    @RequestMapping(value = "/removeMails",method = RequestMethod.POST)
    @ResponseBody
    public String removeMails(@RequestParam String type,
                              @RequestParam String userId,
                              @RequestBody String mailIdList){

        ObjectMapper mapper = new ObjectMapper();
        List<String> lendReco = null;
        try {
            lendReco = mapper.readValue(mailIdList,new TypeReference<List<String>>(){});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        logger.info("====参数type："+type);
        logger.info("====参数userId："+userId);
        logger.info("====参数mailIdList："+ mailIdList);
        int n = mailService.removeMails(Integer.parseInt(userId), type, lendReco);
        return n+"";
    }

    /**
     * 查看指定邮件id的详细信息
     * @param mailId
     * @return
     */
    @RequestMapping("/getMailDetailsByMailId")
    @ResponseBody
    public Mail getMailDetailsByMailId(@RequestParam String mailId){
        return mailService.getMailsById(mailId);
    }

    @RequestMapping(value = "/saveDraftMail",method = RequestMethod.POST)
    @ResponseBody
    public String saveDraftMail(MultipartHttpServletRequest request,@RequestParam String userId){
        //普通表单数据
        String mailId = request.getParameter("mailId");
        String mailType = request.getParameter("mailType");
        String mailStatusid = request.getParameter("mailStatusid");
        String inReceiver = request.getParameter("inReceiver");
        String mailTitle = request.getParameter("mailTitle");
        String mailContent = request.getParameter("mailContent");
        MultipartFile multipartFile = request.getFile("file");//获取文件
        logger.info("===mailType:"+mailType);
        logger.info("===mailStatusid:"+mailStatusid);
        logger.info("===inReceiver:"+inReceiver);
        logger.info("===mailTitle:"+mailTitle);
        logger.info("===mailContent:"+mailContent);
        logger.info("===multipartFile:"+multipartFile.getOriginalFilename());
        logger.info("===userId:"+userId);
        //logger.info("===后缀:"+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")));
        //1、将文件保存进本地
       /* try {
            String before = System.currentTimeMillis()+"";
            String shuffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            multipartFile.transferTo(new FileInfo("E:\\fileupload\\" + before + shuffix));
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //2、将草稿数据进行保存，真正提交时还需包括将邮件保存进邮件详情表、接收者表、文件表
        Mail mail = new Mail();
        mail.setMailContent(mailContent);
        //mail.setMailFileId();
        mail.setMailStatusId(Integer.parseInt(mailStatusid));
        mail.setMailPushUserId(Integer.parseInt(userId));
        mail.setMailTitle(mailTitle);
        mail.setMailType(Integer.parseInt(mailType));
        mail.setReceives(inReceiver);
        return mailService.saveDraftMail(mail,mailId)+"";
    }
    @RequestMapping(value = "/saveSendMail",method = RequestMethod.POST)
    @ResponseBody
    public String saveSendMail(MultipartHttpServletRequest request,@RequestParam String userId){
        //普通表单数据
        String mailId = request.getParameter("mailId");
        String mailType = request.getParameter("mailType");
        String mailStatusid = request.getParameter("mailStatusid");
        String inReceiver = request.getParameter("inReceiver");
        String mailTitle = request.getParameter("mailTitle");
        String mailContent = request.getParameter("mailContent");
        MultipartFile multipartFile = request.getFile("file");//获取文件
        logger.info("===mailType:"+mailType);
        logger.info("===mailStatusid:"+mailStatusid);
        logger.info("===inReceiver:"+inReceiver);
        logger.info("===mailTitle:"+mailTitle);
        logger.info("===mailContent:"+mailContent);
        logger.info("===multipartFile:"+multipartFile);
        logger.info("===userId:"+userId);
        FileInfo fileInfo = null;
        String fileName = null;
        if (!multipartFile.isEmpty()){
            logger.info("=================有提交文件");
            logger.info("===后缀:"+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")));
            //1、将文件保存进本地
            try {
                String before = System.currentTimeMillis()+"";
                String shuffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
                fileName = before + shuffix;
                multipartFile.transferTo(new File("E:\\fileupload\\" + before + shuffix));
                fileInfo = new FileInfo();
                fileInfo.setContentType(multipartFile.getContentType());
                fileInfo.setFileName(before + shuffix);
                fileInfo.setFilePath("E:/fileupload/" + before + shuffix);
                fileInfo.setFileShuffix(shuffix);
                fileInfo.setFileUserId(Integer.valueOf(userId));
                fileInfo.setSize((int)multipartFile.getSize());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //发送邮件
        SendMailUtil.pushmail("1983713964@qq.com","ypyqtkoyujjtbhca",inReceiver,"啊肆肆肆肆肆肆",mailTitle,mailContent,null,fileName);
        //2、将草稿数据进行保存，真正提交时还需包括将邮件保存进邮件详情表、接收者表、文件表
        Mail mail = new Mail();
        mail.setMailContent(mailContent);
        //mail.setMailFileId();
        mail.setMailStatusId(Integer.parseInt(mailStatusid));
        mail.setMailPushUserId(Integer.parseInt(userId));
        mail.setMailTitle(mailTitle);
        mail.setMailType(Integer.parseInt(mailType));
        mail.setReceives(inReceiver);
        String flag = mailService.saveSendMail(mail,fileInfo,mailId)+"";

        return flag;
    }
}
